#!/usr/bin/python3
#-*-coding:utf-8-*-

###############################################################
## Name       : find_key.py
## Author     : gaojiaming
## Date       : Sat Dec 10 17:44:05 CST 2022
## Description:
##
##
###############################################################

import sys
import os
import re
import argparse
import subprocess
from   pathlib import Path

def input_args_proc():#{{{
  parser = argparse.ArgumentParser(description="argparse info")
  parser.add_argument('-o', action='store_true', default=False, help='open this script')
  parser.add_argument('-k', help='key word')
  parser.add_argument('-f', default="./sim_base/log/sim.log", help='log path')
  parser.add_argument('-n', type=int, default=1, help='return file num')
  result = parser.parse_args()
  if result.o == True:
      os.system("gvim %s" % __file__)
      sys.exit(0)

  if not result.k:
      raise ValueError("No key word input")

  path = Path(result.f)
  if not path.is_file():
      raise ValueError(f"{path} not exists or not file")

  return result.k, result.f, result.n
pass#}}}

def change_to_list(file):
  find_file_list = []
  with open(file, "r") as hd:
    handle = hd.readlines()
    for line in handle:
      re_cmp_file = re.search(r"file \'(.*)\'", line)
      if re_cmp_file:
        find_file_list.append(re_cmp_file.group(1))
  return find_file_list
pass

def find_key(key, file_list, num):
  if not isinstance(file_list, list):
        raise TypeError("file_list type error")
  find_cnt = 0
  for file in file_list:
    command = "grep -l -E {0} {1}".format(key, file)
    output = os.popen(command).read()
    if output != "":
      print(output.strip())
      find_cnt += 1
    if find_cnt >= num:
      break
pass

def main():
  (key, file, num) = input_args_proc()
  find_file_list = change_to_list(file)
  find_key(key, find_file_list, num)
pass

if __name__ == "__main__":
  print("%s is working" % __file__)
  main()
